package com.lzq.shiro.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lzq.shiro.config.Constant;
import com.lzq.shiro.entity.ResponseEntity;
import com.lzq.shiro.entity.SysRole;
import com.lzq.shiro.entity.UserInfo;
import com.lzq.shiro.entity.UserRole;
import com.lzq.shiro.mapper.SysRoleMapper;
import com.lzq.shiro.mapper.SysUserRoleMapper;
import com.lzq.shiro.mapper.UserInfoMapper2;
import com.lzq.shiro.service.UserInfoService2;
import com.lzq.shiro.util.MD5Util;
import com.lzq.shiro.vo.RspUtil;

@Service
public class UserInfoService2Impl implements UserInfoService2{
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private UserInfoMapper2 userInfoMapper2;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	
	@Autowired
	private SysRoleMapper sysRoleMapper;
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public Map<String, Object> register(UserInfo userInfo) throws Exception {
		// 验证手机号码
		UserInfo userInfoDb = userInfoMapper2.findByMobile(userInfo.getMobile());
		if(userInfoDb != null)
			return RspUtil.rspErrMap(ResponseEntity.MOBILE_ALR_EXIST.getCode(), ResponseEntity.MOBILE_ALR_EXIST.getMessage());
		// 保存用户
		
		userInfo.setSalt(userInfo.getUsername() + userInfo.getMobile());
		String password = MD5Util.createCredential(userInfo.getPassword(), userInfo.getCredentialsSalt());
		userInfo.setPassword(password);
		userInfo.setState(0);
		int addUserFlag = userInfoMapper2.addUser(userInfo);
		if(addUserFlag > 0) {
			int genKey = userInfo.getUid();
			logger.info("用户:" + genKey + "保存成功");
			// 查询用户默认权限
			SysRole sysRole = new SysRole();
			sysRole.setRole(Constant.DEFAULT_USER_ROLE);
			List<SysRole> sysRoleList = sysRoleMapper.selectRole(sysRole);
			// 初始化用户权限
			if(sysRoleList.size() == 1) {
				UserRole userRole = new UserRole();
				userRole.setRoleId(sysRoleList.get(0).getId());
				userRole.setUid(genKey);
				Integer updUserRoleFlag = sysUserRoleMapper.insert(userRole);
				if(updUserRoleFlag == 1)
					logger.info("初始化用户：" + genKey + "成功");
			}
			return RspUtil.rspMap("用户注册成功");
		} 
		return RspUtil.rspErrMap(ResponseEntity.REGISTER_FAILED.getCode(), ResponseEntity.REGISTER_FAILED.getMessage());
	}

	@Override
	public UserInfo query(UserInfo queryParams) throws Exception {
		return userInfoMapper2.queryByParams(queryParams);
	}
	
	

}
